<template>
  <keep-alive>
    <el-form :model="form" label-width="90px">
      <el-row>
        <el-col :span="5">
          <el-button type="success" @click="CreateTask" style="float: right;margin-right: 20px">保存</el-button>
          <el-form-item label="任务名" prop="name">
            <el-input v-model="form.name" width="200px"></el-input>
          </el-form-item>

          <el-form-item label="当前项目" prop="name">
            <el-input v-model="project.name" width="200px" disabled></el-input>
          </el-form-item>

          <el-form-item label="代码分支">
            <el-tooltip :content="'当前分支：'+ form.branch" placement="top-start">
              <el-switch v-model="branch"></el-switch>
            </el-tooltip>
          </el-form-item>

          <template v-if="branch">
            <el-form-item label="分支名">
              <el-input clearable v-model="form.branch"></el-input>
            </el-form-item>
          </template>

          <el-form-item label="环境">
            <el-select v-model="form.env" placeholder="请选择运行环境" multiple>
              <el-option v-for="item in env_list" :key="item" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>

          <el-form-item label="定时任务" prop="iscron">
            <el-switch v-model="form.switch"></el-switch>
          </el-form-item>

          <template v-if="form.switch">
            <el-form-item label="cron表达式" prop="cron">
              <el-input v-model="form.spec"></el-input>
              <el-switch v-model="edit" style="display: inline" :active-action-icon="View"
                         :inactive-action-icon="Hide">
              </el-switch>
            </el-form-item>
          </template>

          <el-form-item label="全局参数" class="top-item">
            <el-input
                v-model="form.param"
                :autosize="{ minRows: 6, maxRows: 24}"
                label-position="top"
                type="textarea"
                placeholder="请输入JSON格式的字符串"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <TaskCheckBox v-model:data="task_group_info" @UpdateTask="update_curtask"></TaskCheckBox>
        </el-col>
        <el-col :span="15">
          <template v-if="task_type=='API'">
            API
          </template>
          <template v-else-if="task_type=='监控'">
            监控
          </template>
          <template v-else-if="task_type=='SHELL命令行'">
            SHELL命令行
          </template>
          <template v-else>
            <div id="case_table">
              <div style="margin-left: 10px;margin-bottom: 3px">
                <el-button type="success" plain @click="SelectCase">用例选择</el-button>

                <!--                <el-badge :value="tableData.length" class="item">-->
                <!--                  <el-button type="success" plain @click="CaseAnalysis">用例分析</el-button>-->
                <!--                </el-badge>-->

                <el-button type="danger" plain @click="RemoveCases">删除</el-button>
                <el-text class="mx-1" size="large" type="info"
                         style="margin-left: 20px;color: #1e73b7;font-weight: bold">
                  当前任务：{{ task_group_info.cur_task.name }}
                </el-text>
              </div>

              <Table v-model:data="task_group_info.cur_task.testcases" @selection-change="handleSelectionChange"
                     max_height="740px">
                <el-table-column type="selection" width="55"/>
                <el-table-column prop="id" label="ID" width="100"/>
                <el-table-column prop="name" label="用例名" width="280"/>
                <el-table-column prop="dtime" label="标签"/>
                <el-table-column prop="dtime" label="问题数"/>
                <el-table-column label="操作" width="240">
                  <template #default="scope">
                    <el-button link plain @click="MoveDown(scope.row)" type="info">下移</el-button>
                    <el-button link plain @click="MoveUp(scope.row)" type="info">上移</el-button>
                    <el-button link plain @click="CopyOne(scope.row)" type="info">复制</el-button>
                    <el-button link plain @click="RemoveCase(scope.$index)" type="danger">删除</el-button>
                  </template>
                </el-table-column>
              </Table>
            </div>
          </template>
        </el-col>

      </el-row>
    </el-form>
  </keep-alive>
  <el-dialog v-model="edit" title="CRON表达式生成器" width="25%" center class="dialog" draggable top="10vh" model=false>
    <Cron v-model:value="form.spec"></Cron>
  </el-dialog>

  <el-drawer
      ref="drawerRef"
      v-model="select_case"
      title="用例选择"
      :before-close="handleClose"
      direction="rtl"
      size="60%"
      class="demo-drawer">
    <div id="case_select">
      <el-tabs type="border-card">
        <el-tab-pane label="用例树">
          <div class="content">
            <Tree v-model:tool="testcase" v-model:meau="case_meau" @ChangeFather="ChangeFather" ref="update_api"></Tree>
          </div>

        </el-tab-pane>
        <el-tab-pane label="根据标签">

        </el-tab-pane>
        <el-tab-pane label="手动添加">

        </el-tab-pane>
        <el-tab-pane label="Task">

        </el-tab-pane>
      </el-tabs>
    </div>
  </el-drawer>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue'
import {task} from "../js/task";
import Tree from "@/view/dashboard/cicd/components/case_select.vue";
import {env} from '../../laboratory/env_api'
import {useRoute} from "vue-router"
import Cron from '@/components/common/Cron.vue'
import Table from '@/components/common/Table.vue';
import {Hide, View} from '@element-plus/icons-vue'
import {case_meau, testcase} from "../testcase_api"
import {ElMessage, ElMessageBox, ElTree} from 'element-plus'
import TaskCheckBox from '@/components/common/checkbox/task_checkbox.vue'
import {useUserStore} from '@/pinia/modules/user'

const store = useUserStore()
const treeRef = ref<InstanceType<typeof ElTree>>()
let page = reactive({"page": 1, "size": 15, "total": 0, id: undefined})
const route = useRoute()

const task_type = ref("")

const create = ref(true)
const select_case = ref(false)
const group_cases = ref({})

const env_list = ref([])
const multipleSelection = ref([])
const project = ref({name: "", id: ""})
const task_group_info = ref({
  cur_task: {name: "", testcases: [], isActive: false},
  cur_group: {name: ""},
  taskgroups: [],

})

const ChangeFather = async (testcases) => {
  task_group_info.value.cur_task['testcases'] = task_group_info.value.cur_task['testcases'].concat(testcases)
}

const form = ref({
  name: "aaaaaa",
  branch: "main",
  email: "",
  switch: false,
  env: [],
  spec: "",
  project_id: "",
  retryStrategy:"",
  taskgroup: task_group_info.value.taskgroups,
  param: "{}",
})


const tableData = ref([])
const edit = ref(false)
const branch = ref(false)

const ListEnv = async () => {
  var envs = await env.List(page)
  env_list.value = envs.data
}

onMounted(async () => {
  ListcaseMeau()
  ListEnv()

  tableData.value = []
  // 修改任务
  if (route.query.data != undefined) {
    create.value = false
    let taskname = route.query.data
    let data = await task.Detail(taskname)

    form.value.name = data.data.name
    form.value.branch = data.data.branch
    form.value.switch = data.data.switch
    form.value.param = data.data.param
    form.value.env = data.data.env
    form.value.retryStrategy = data.data.retryStrategy

    // 任务开启的任务分组功能
    task_group_info.value.taskgroups = data.data.taskgroup

    var task_groups = task_group_info.value.taskgroups

    for (var i in task_groups) {
      if (!task_groups[i].hasOwnProperty("tasks")) {
        continue
      }

      var tasks = task_groups[i].tasks
      for (var t in tasks) {
        if (tasks[t]['testcases'].length != 0) {
          task_group_info.value.cur_task = tasks[t]
          task_group_info.value.cur_task.isActive = true
          break
        }
      }
    }
  }

  project.value = await store.GetProject()
  if (project.value != null) {
    form.value.project_id = project.value.id
  }
})

//切换任务
const update_curtask = () => {
  resetChecked(task_group_info.value.cur_task['testcases']) //切换任务的时候，更新tree与表格数据
  if (!treeRef.value!) {
    if (task_group_info.value.cur_group.name != undefined && task_group_info.value.cur_task.name != undefined) {
      var name = task_group_info.value.cur_group.name + "/" + task_group_info.value.cur_task.name
      if (group_cases.hasOwnProperty(name)) {
        tableData.value = group_cases.value[name]
        tableData.value = group_cases.value[name].filter((item) => {
          return task_group_info.value.cur_task.testcases.indexOf(item.id) !== -1
        })
      }
    }
  }
}

const SelectCase = () => {
  resetChecked(task_group_info.value.cur_task['testcases'])
  if (task_group_info.value.cur_task.name.length == 0) {
    ElMessage.warning("请选择任务组")
    return
  }
  select_case.value = true
}

const handleCheckChange = async (data, checked, indeterminate) => {
  if (tableData.value == undefined) {
    tableData.value = []
  }
  var cur_task = task_group_info.value.cur_task
  data['taskname'] = cur_task.name
  if (data.caseid != undefined) {
    if (checked == true) {
      tableData.value.push(data)
      if (cur_task.name.length != 0) {
        if (cur_task['testcases'].indexOf(data['id']) == -1)
          await task_group_info.value.cur_task['testcases'].push(data['id'])
      }
    } else {
      RemoveCase(data)
    }
  }
}

const resetChecked = (data) => {
  if (treeRef.value!) {
    treeRef.value!.setCheckedKeys(data, false)
  }
}

const RemoveCase = (index) => {
  task_group_info.value.cur_task.testcases = task_group_info.value.cur_task.testcases.filter((_, i) => {
    return index !== i
  })
}

const RemoveCases = () => {
  let id_list = []
  for (let i in multipleSelection.value) {
    let data = multipleSelection.value[i]
    id_list.push(data.id)
    task_group_info.value.cur_task.testcases = task_group_info.value.cur_task.testcases.filter((item) => {
      return item.id !== data.id
    })
  }
  task_group_info.value.cur_task.testcases = id_list
}

const MoveDown = (el) => {
  const index = task_group_info.value.cur_task.testcases.indexOf(el);
  if (index === -1 || index === task_group_info.value.cur_task.testcases.length - 1) return [...task_group_info.value.cur_task.testcases]; // 元素不存在或已在最左
  const newArr = [...task_group_info.value.cur_task.testcases];
  [newArr[index], newArr[index + 1]] = [newArr[index + 1], newArr[index]]; // 交换位置
  task_group_info.value.cur_task.testcases = newArr

}

const MoveUp = (el) => {
  const index = task_group_info.value.cur_task.testcases.indexOf(el);
  if (index === -1 || index === 0) return [...task_group_info.value.cur_task.testcases]; // 元素不存在或已在最左
  const newArr = [...task_group_info.value.cur_task.testcases];
  [newArr[index - 1], newArr[index]] = [newArr[index], newArr[index - 1]]; // 交换位置
  task_group_info.value.cur_task.testcases = newArr;
}

const CopyOne = (el) => {
  task_group_info.value.cur_task.testcases.push(el)
}

const MeauTree = ref([])

const ListcaseMeau = async () => {
  let res = await case_meau.List()
  MeauTree.value = res.data
}

const handleSelectionChange = (val) => {
  multipleSelection.value = val
}


const CreateTask = async () => {
  if (form.value.name.length == 0) {
    ElMessage.info("请输入任务名称")
    return
  }
  if (form.value.switch && !form.value.spec) {
    ElMessageBox.confirm("开启了定时任务但未填写CRON表达式，是否继续填写？").then(() => {
      return
    }).catch((error) => {
      form.value.switch = false
    })
    return
  }

  var task_groups = JSON.parse(JSON.stringify(task_group_info.value.taskgroups));
  for (var i in task_groups) {
    if (!task_groups[i].hasOwnProperty("tasks")) {
      continue
    }

    var tasks = task_groups[i].tasks
    for (var t in tasks) {
      let id_list = []
      for (var c in tasks[t]['testcases']) {
        id_list.push({"id": tasks[t]['testcases'][c].id})
      }
      tasks[t]['testcases'] = id_list
      delete tasks[t].isActive
    }
  }
  form.value.taskgroup = task_groups
  // var env = []
  // for (var i in form.value.env) {
  //   env.push({"id": form.value.env[i]})
  // }
  // console.log(env)
  // var form_copy = JSON.parse(JSON.stringify(form.value));
  // form_copy.env = env
  if (create.value === true) {
    await task.Create(form.value)
  } else {
    await task.Modify(form.value)
  }
}
const handleClose = () => {
  select_case.value = false
}
</script>

<style scoped>
@import "@/styles/table_common.scss";

.el-form .el-input, .el-select {
  width: 200px;
}

.el-form, .el-row, .el-col {
  height: 100%;
}

.el-col {
  border-right: 1px #e3d7d7 solid;
}

.el-col:last-child {
  border-right: none;
}

.el-col:nth-child(2) {
  padding: 25px 0;
  margin: 0;
}

.el-col:nth-child(3) {
  padding: 20px 0;
  margin: 0;
}

#case_select {
  height: 480px;
  overflow: auto;
}

.top-item {
  flex-flow: column;
}


#custom-menu ul li {
  padding: 8px 16px;
  cursor: pointer;
  list-style: none;
}

.tree_operation > .el-icon {
  padding-right: 5px;
}

#custom-menu ul li:hover {
  background-color: rgba(194, 191, 191, 0.92);
}

:deep(.el-tabs__content) {
  max-height: 400px !important;
  overflow: auto;
}

.folder {
  color: #214232;
  font-size: 14px;
}
</style>